package com.wyz.socket.core.base;

import com.wyz.socket.core.api.IoProvider;

import java.nio.channels.SocketChannel;

public abstract class ProviderCallback extends IoTask implements Runnable {
    protected volatile IoArgs args;
    private final IoProvider provider;

    public ProviderCallback(IoProvider provider, SocketChannel channel, int ops) {
        super(channel, ops);
        this.provider = provider;
    }

    @Override
    public final void run() {
        final IoArgs args = this.args;
        this.args = null;
        try {
            if (onRun(args)) {
                provider.register(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
            onThrowException(e);
        }
    }

    @Override
    public boolean onProcess() {
        final IoArgs args = this.args;
        this.args = null;
        return onRun(args);
    }

    protected abstract boolean onRun(IoArgs args);

    public void checkAttachSuccess() {
        if (args != null) {
            throw new IllegalStateException(" handlerCallback attach != null");
        }
    }
}